<div class="d-flex justify-content-start flex-wrap gap-3">
{% for mv in mcmvs %}
<!-- jinja2 中获取循环中的 index; 设置video的 ID属性 -->
{% set vid = 'mv' + loop.index|string %}
<div class="card cardwh">
    
    <a href="{{ mv.url }}" data-fancybox="group" data-caption="{{ mv.srcfile }}">
        <video class="video-custom-size" controls="0" poster="" id="{{ vid }}">
            <source src="{{ mv.url }}" type="video/mp4">
        </video> 
        <canvas id="poster-{{ vid }}" style="display: none;"></canvas>
        
    </a>
    <div class="card-body">
        <p class="card-text">{{ mv.srcfile }} ({{ mv.size }} M)</p>
    </div>
</div>
{% endfor %}
<script>
    // 为某个视频元素添加 poster，参数为视频元素对象
    function addPoster(video) {
        mvid = video.id;
        const posterCanvas = document.getElementById('poster-' + mvid);
        const ctx = posterCanvas.getContext('2d');

        video.addEventListener('loadedmetadata', function () {
            const frameNumber = 5;
            const frameTime = frameNumber / video.videoWidth;
            video.currentTime = frameTime;

            video.addEventListener('seeked', function () {
                posterCanvas.width = video.videoWidth;
                posterCanvas.height = video.videoHeight;
                ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
            });

            video.currentTime = frameTime;
        });

        return posterCanvas;
    }

    // 获取所有的视频元素
    const videos = document.querySelectorAll('video');
    videos.forEach(video => {
        // 为每个视频元素添加 poster
        addPoster(video);
    });

</script>
</div>

<div class="d-flex justify-content-start mt-3">
    <!-- bootstrap 分页 -->
    <nav aria-label="Page navigation example">
        <ul class="pagination justify-content-end">
            {{ pagehtml | safe }}
        </ul>
    </nav>
</div>